package com.xxx.nio.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import com.xxx.nio.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 阻塞模式Server端
 */
@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 0.创建ByteBuffer缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(16);

        // 1.创建Server端的SocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 2.绑定Server端监听端口
        ssc.bind(new InetSocketAddress(8080));

        // 3.channel集合
        List<SocketChannel> channelList = new ArrayList<>();

        while (true) {
            // 4.创建SocketChannel，建立与Client端连接
            log.info("Server waiting for connecting...");
            SocketChannel sc = ssc.accept();   // 阻塞模式，直到Client连接请求过来
            log.info("Server connected success from {}", sc);
            channelList.add(sc);
           // 5.循环遍历所有的Channel，读取每一个Channel里的数据
            for (SocketChannel channel : channelList) {
                log.info("before read...{}", channel);
                channel.read(buffer);    // 阻塞模式，将Channel里的内容读取到缓冲区
                buffer.flip();  // 切换到读取模式
                ByteBufferUtil.debugRead(buffer);  // 打印buffer
                buffer.clear(); // 清空buffer（重置buffer到写模式）
                log.info("after read...{}", channel);
            }
        }

    }
}
